package com.luwanglin.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luwanglin.eduservice.entity.EduSubject;
import com.luwanglin.eduservice.entity.excel.ExcelSubjectData;
import com.luwanglin.eduservice.service.impl.EduSubjectServiceImpl;
import com.luwanglin.commonutils.exception.GuliException;

/**
 * @author lwl
 */
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {
    public SubjectExcelListener(EduSubjectServiceImpl eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    public SubjectExcelListener() {
    }

    EduSubjectServiceImpl eduSubjectService;


    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if (excelSubjectData == null) {
            throw new GuliException(20001, "no data in files");
        }
        EduSubject eduSubject1 = this.existOneSubject(excelSubjectData.getOneSubjectName());
        if (eduSubject1 == null) {
            eduSubject1 = new EduSubject();
            eduSubject1.setParentId("0");
            eduSubject1.setTitle(excelSubjectData.getOneSubjectName());
            eduSubject1.setSort(1);
            eduSubjectService.save(eduSubject1);
        }
        EduSubject existTwoSubject = this.existTwoSubject(excelSubjectData.getTwoSubjectName(), eduSubject1.getId());
        if (existTwoSubject == null) {
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(eduSubject1.getId());
            existTwoSubject.setTitle(excelSubjectData.getTwoSubjectName());
            existTwoSubject.setSort(2);
            eduSubjectService.save(existTwoSubject);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断一级分类是否重复
    private EduSubject existOneSubject(String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        return eduSubjectService.getOne(wrapper);
    }

    //判断second级分类是否重复
    private EduSubject existTwoSubject(String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        return eduSubjectService.getOne(wrapper);
    }

}
